import { HttpClient } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { FormArray, FormControl, FormGroup, Validators } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { Observable } from 'rxjs';
import { CommonService } from 'src/app/service/common/common.service';
import { FeeEnquiryService } from 'src/app/service/fee-enquiry/fee-enquiry.service';
import { MessageService } from 'src/app/service/message.service';
import { UsageCodeData, UserBindService } from 'src/app/service/user-bind.service';
import { NAME_REG } from 'src/app/utils/regExp';

@Component({
  selector: 'app-step-apply',
  templateUrl: './step-apply.component.html',
  styleUrls: ['./step-apply.component.scss']
})
export class StepApplyComponent implements OnInit {

  constructor(
    private feeEnquiryService: FeeEnquiryService,
    private bindUser: UserBindService,
    private http: HttpClient,
    private message: MessageService,
    private router: Router,
    private route: ActivatedRoute,
    private common: CommonService
  ) { }

  formData: FormGroup = new FormGroup({
    isSecret: new FormControl(true),
    setId: new FormControl('50'),
    infoSources: new FormControl('WT'),
    userCode: new FormControl('', [Validators.required]),
    userName: new FormControl(''),
    userAddr: new FormControl({ value: '', disabled: true }),
    contact: new FormControl('', [Validators.required, Validators.pattern(NAME_REG)]),
    contactTel: new FormControl('', [Validators.required, Validators.pattern(/^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\d{8})$/)]),
    personNum: new FormControl('1', [Validators.required]),
    certificateNumber: new FormControl('', [Validators.required]),
    certificateFile1: new FormControl('', [Validators.required]),
    detailList: new FormArray([
      new FormGroup({
        name: new FormControl('', [Validators.required, Validators.pattern(NAME_REG)]),
        relation: new FormControl('', Validators.required),
        certificateNumber: new FormControl('', Validators.required),
        certificateType: new FormControl('', Validators.required),
        certificateFile1: new FormControl('', Validators.required)
      })
    ])
  })

  ngOnInit() {
    this.common.setRightInfoVisible(true)
    
    this.getUserCodeList()
    this.getRelationList()
    this.getCertificateTypeList()

    this.route.queryParams.subscribe((params: any) => {
      const id = params.id
      const isDetail = params.isDetail
      if(id && isDetail === 'false'){
        this.formPreview(id)
      }
    })
  }

  isPreview: boolean = false;
  formPreview(id: string){
    this.formData.disable()
    this.uploadAvailable = false
    this.isPreview = true

    const url = `/api/gsxmcp/cf/mg/v1.0/ladderWater/detail/${id}`
    this.http.get(url).subscribe(res => {
      console.log(res)
      this.formData.patchValue(res)

      this.detailList.controls.forEach(control => {
        control.disable()
      })
    })
  }

  onUserCodeChange(value: string){
    let res = this.userCodeList.find(item => item.usageCode === value)
    if(res){
      this.formData.patchValue({ userAddr: res.address })
      this.formData.patchValue({ userName: res.name })
    }
  }
  onCertificateTypeChange(value: any, control: any){
    const field = control.get('certificateNumber')
    const name = this.certificateTypeList.find((item: any) => item.id === value)
    if(name.name.indexOf('身份证') !== -1){
      field.setValidators([
        Validators.required, 
        Validators.pattern(/^(\d{18,18}|\d{17,17}X)$/),
      ])
    }else{
      field.setValidators([Validators.required])
    }
    field.updateValueAndValidity()
  }

  // 文件上传处理
  uploadAvailable: boolean = true
  uploadBack(value: any, control: any){
    if(control){
      control.setValue(value)
    }
  }

  // 提交
  btnLoading: boolean = false;
  onSubmit(){
    console.log(this.formData.getRawValue())

    console.log(this.validateForm())

    if(!this.validateForm()) return 

    this.btnLoading = true
    this.addStepApply(this.formData.getRawValue()).subscribe(res => {

      this.btnLoading = false;
      this.formData.disable()
      this.uploadAvailable = false
      this.message.success('提交成功')
    }, error => {
      this.message.createErrorMessage(error)
    })
  }
  
  validateForm(){
    let flag = true
    const controls = this.formData.controls;
    for (let i in controls) {
      controls[i].markAsTouched();
      controls[i].updateValueAndValidity();
    }

    const detailControls = this.detailList.controls as Array<FormGroup>
    for (let i in detailControls) {
      let detailControl = detailControls[i].controls
      for(let i in detailControl){
        detailControl[i].markAsTouched();
        detailControl[i].updateValueAndValidity();
      }
    }

    for(let i in controls){
      if(controls[i].invalid){
        flag = false
        break
      }
    }
    
    for(let i in detailControls){
      if(detailControls[i].invalid){
        flag = false
        break
      }
    }
    return flag
  }
  addStepApply(params: any): Observable<any>{
    const url = '/api/gsxmcp/cf/mg/v1.0/ladderWater'
    return this.http.post(url, params)
  }
  onReset(){
    this.message.confirmModal('确定清空表单并返回上一页吗?', () => {
      this.formData.reset()
      history.go(-1)
    })
  }
  onBack(){
    history.go(-1)
  }

  // 动态添加用水人
  onPersonNumChange(value: number){
    const num = value - this.detailList.length
    
    if(num > 0){
      for(let i = 0; i < num; i++){
        let detail = new FormGroup({
          name: new FormControl('', [Validators.required, Validators.pattern(NAME_REG)]),
          relation: new FormControl('', Validators.required),
          certificateNumber: new FormControl('', Validators.required),
          certificateType: new FormControl('', Validators.required),
          certificateFile1: new FormControl('', Validators.required)
        })
        this.detailList.push(detail)
      }
    }

    if(num < 0){
      for(let i = 0; i < -num; i++){
        this.detailList.removeAt(this.detailList.length - 1)
      }
    }
  }
  deletePerson(index: any){
    if(this.isPreview) return
    this.detailList.removeAt(index)
  }

  // 获取用户编号列表
  userCodeList: Array<UsageCodeData> = []
  certificateTypeList: any;
  relationList: any = []
  getUserCodeList(){
    this.bindUser._getBindList().subscribe((res: Array<UsageCodeData>) => {
      console.log(res)
      this.userCodeList = res
    })
  }
  getCertificateTypeList(){
    this.common.dictQuery('证件类型').subscribe({
      next: res => {
        this.certificateTypeList = res
      },
      error: error => {

      }
    })
  }
  getRelationList(){
    this.getRelations().subscribe(res => {
      this.relationList = res
    })
  }
  getRelations(): Observable<any>{
    // let url = '/api/gsxmcp/cf/mg/v1.0/funcData/param/1'
    let url = '/api/gsxmcp/bd/cm/v1.0/codeItems/D123'
    return this.http.get(url);
  }

  get detailList(){
    return this.formData.get('detailList') as FormArray
  }

}

// 获取详情
// let api = "/api/gsxmcp/cf/mg/v1.0/ladderWater/detail/" + `${this.businessType}`;
//  
